<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.7.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="有时我们需要在APP中控制WIFI和数据连接的开关，在Android中，是有相应的接口可以实现这一功能的。 控制WIFI开关控制WIFI开关需要使用WifiManager这一系统服务。首先我们通过代码获取到它：">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android中使用代码控制Wifi及数据连接网络开关">
<meta property="og:url" content="https://ricky9090.github.io/2015/12/10/android_control_wifi/index.html">
<meta property="og:site_name" content="Ricky&#39;s Blog">
<meta property="og:description" content="有时我们需要在APP中控制WIFI和数据连接的开关，在Android中，是有相应的接口可以实现这一功能的。 控制WIFI开关控制WIFI开关需要使用WifiManager这一系统服务。首先我们通过代码获取到它：">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-06-11T08:46:43.909Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android中使用代码控制Wifi及数据连接网络开关">
<meta name="twitter:description" content="有时我们需要在APP中控制WIFI和数据连接的开关，在Android中，是有相应的接口可以实现这一功能的。 控制WIFI开关控制WIFI开关需要使用WifiManager这一系统服务。首先我们通过代码获取到它：">
  <link rel="canonical" href="https://ricky9090.github.io/2015/12/10/android_control_wifi/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Android中使用代码控制Wifi及数据连接网络开关 | Ricky's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ricky's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">A long way to go.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://ricky9090.github.io/2015/12/10/android_control_wifi/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ricky">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ricky's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">Android中使用代码控制Wifi及数据连接网络开关

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2015-12-10 23:00:17" itemprop="dateCreated datePublished" datetime="2015-12-10T23:00:17+08:00">2015-12-10</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2018-06-11 16:46:43" itemprop="dateModified" datetime="2018-06-11T16:46:43+08:00">2018-06-11</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>有时我们需要在APP中控制WIFI和数据连接的开关，在Android中，是有相应的接口可以实现这一功能的。<br><br></p>
<h4 id="控制WIFI开关"><a href="#控制WIFI开关" class="headerlink" title="控制WIFI开关"></a><strong>控制WIFI开关</strong></h4><p>控制WIFI开关需要使用WifiManager这一系统服务。首先我们通过代码获取到它：<br><a id="more"></a><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);</span><br></pre></td></tr></table></figure></p>
<p>通过WifiManager提供的接口，我们就可以实现控制WIFI的开关——我们首先判断当前WIFI的状态，如果是打开状态，则调用接口关闭；反之如果当前是关闭状态，则调用接口打开：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (wifiManager.isWifiEnabled()) &#123;</span><br><span class="line">    wifiManager.setWifiEnabled(<span class="keyword">false</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    wifiManager.setWifiEnabled(<span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>编写代码之后，我们还需要在AndroidManifest中声明相应的权限才能使代码正确生效，否则会抛出  <strong>java.lang.SecurityException</strong>  异常。其中<br>isWifiEnabled接口需要申请  <strong>android.permission.ACCESS_WIFI_STATE</strong>  权限<br>setWifiEnabled接口需要申请<strong>android.permission.CHANGE_WIFI_STATE</strong>权限：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.ACCESS_WIFI_STATE"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.CHANGE_WIFI_STATE"</span>/&gt;</span></span><br></pre></td></tr></table></figure></p>
<p><br><br><br></p>
<h4 id="控制数据连接开关"><a href="#控制数据连接开关" class="headerlink" title="控制数据连接开关"></a><strong>控制数据连接开关</strong></h4><p>控制数据连接开关的情况稍复杂一些——首先Android 5.0以后的版本与4.4及以前版本接口不同；其次这些接口没有公开出来，我们需要通过反射的方法调用它们。<br></p>
<p><strong>Android 4.4及以前版本</strong></p>
<p>在Android 4.4及以前版本中，控制数据连接开关的接口隐藏在ConnectivityManager系统服务中，因此我们还是要先获取到相应系统服务：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);</span><br></pre></td></tr></table></figure></p>
<p>在这个服务中，有getMobileDataEnabled和setMobileDataEnabled两个接口，分别是获取连接状态和设置连接的状态。<br>这两个接口的声明如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">getMobileDataEnabled</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMobileDataEnabled</span><span class="params">(<span class="keyword">boolean</span> enabled)</span></span></span><br></pre></td></tr></table></figure></p>
<p>因此我们分别通过反射方法调用这些接口，并同样先判断状态，再进行开关控制：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Class[] getArgArray = <span class="keyword">null</span>;</span><br><span class="line">Class[] setArgArray = <span class="keyword">new</span> Class[] &#123;<span class="keyword">boolean</span>.class&#125;;</span><br><span class="line"></span><br><span class="line">Object[] getArgInvoke = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Method mGetMethod = conManager.getClass().getMethod(<span class="string">"getMobileDataEnabled"</span>, getArgArray);</span><br><span class="line">    Method mSetMethod = conManager.getClass().getMethod(<span class="string">"setMobileDataEnabled"</span>, setArgArray);</span><br><span class="line">    <span class="keyword">boolean</span> isOpen = (Boolean) mGetMethod.invoke(conManager, getArgInvoke);</span><br><span class="line">    <span class="keyword">if</span> (isOpen) &#123;</span><br><span class="line">        mSetMethod.invoke(conManager, <span class="keyword">false</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        mSetMethod.invoke(conManager, <span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>同样的，调用这些接口需要相应权限：<br>getMobileDataEnabled需要<strong>android.permission.ACCESS_NETWORK_STATE</strong>权限<br>setMobileDataEnabled需要<strong>android.permission.CHANGE_NETWORK_STATE</strong>权限<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.ACCESS_NETWORK_STATE"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.CHANGE_NETWORK_STATE"</span>/&gt;</span></span><br></pre></td></tr></table></figure></p>
<p><br></p>
<p><strong>Android 5.0及以后版本</strong></p>
<p>以上的代码在Android 5.0中运行没有任何效果，并且还会抛出“NoSuchMethod”异常。这是因为在Andrfoid 5.0中，原有的两个方法被废弃掉了，新的接口转移到了TelephonyManager系统服务中，因此我们先获得它：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">TelephonyManager teleManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);</span><br></pre></td></tr></table></figure></p>
<p>新的接口是getDataEnabled和setDataEnabled，形式和以前完全类似（实际还有两个参数更多的方法，这里就省略了，后面会说明）：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">getDataEnabled</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setDataEnabled</span><span class="params">(<span class="keyword">boolean</span> enable)</span></span></span><br></pre></td></tr></table></figure></p>
<p>我们同样使用反射方法去调用：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Class[] getArgArray = <span class="keyword">null</span>;</span><br><span class="line">Class[] setArgArray = <span class="keyword">new</span> Class[] &#123;<span class="keyword">boolean</span>.class&#125;;</span><br><span class="line">Object[] getArgInvoke = <span class="keyword">null</span>;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Method mGetMethod = teleManager.getClass().getMethod(<span class="string">"getDataEnabled"</span>, getArgArray);</span><br><span class="line">    Method mSetMethod = teleManager.getClass().getMethod(<span class="string">"setDataEnabled"</span>, setArgArray);</span><br><span class="line">    <span class="keyword">boolean</span> isOpen = (Boolean) mGetMethod.invoke(teleManager, getArgInvoke);</span><br><span class="line">    <span class="keyword">if</span> (isOpen) &#123;</span><br><span class="line">        mSetMethod.invoke(teleManager, <span class="keyword">false</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        mSetMethod.invoke(teleManager, <span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这两个接口同样也需要特定权限，其中<br><br>getDataEnabled需要权限<strong>android.permission.READ_PHONE_STATE</strong><br><br>setDataEnabled需要权限<strong>android.permission.MODIFY_PHONE_STATE</strong><br></p>
<p>添加权限以后会发现IDE会报错，说MODIFY这个权限<strong>Permission is only granted to system apps</strong>。这样看来Android 5.0以后只有系统APP才可以控制手机数据连接的开关了。</p>
<p>总结一下：<br><br>1.控制WIFI开关需要WifiManager系统服务，直接调用相关接口即可，此外还需要声明相应权限。<br><br>2.控制数据连接开关无论Android版本，由于系统没有公开这一API，因此都需要通过反射调用来实现。同时还要声明相应权限。此外对于Android 4.4以前版本，这一隐藏方法在ConnectivityManager系统服务中，系统/非系统应用均可调用；在Android 5.0以后版本中，更改连接状态则需要系统级APP的权限才可支持。</p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/android/" rel="tag"># android</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2015/12/05/horizontalscrollview_note/" rel="next" title="Android中使用HorizontalScrollView横向滑动布局">
                  <i class="fa fa-chevron-left"></i> Android中使用HorizontalScrollView横向滑动布局
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2015/12/28/android_screen_size/" rel="prev" title="Android获取屏幕宽高信息">
                  Android获取屏幕宽高信息 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#控制WIFI开关"><span class="nav-number">1.</span> <span class="nav-text">控制WIFI开关</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#控制数据连接开关"><span class="nav-number">2.</span> <span class="nav-text">控制数据连接开关</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Ricky</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/ricky9090" title="GitHub &rarr; https://github.com/ricky9090" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ricky</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.7.1</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

</body>
</html>
